package com.zhenyi.fenda.core.ws;

import org.hashids.Hashids;

import com.fenda.common.model.FdRoom;
import com.fenda.common.model.FdUser;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;

import cn.hutool.core.lang.Singleton;
import cn.hutool.json.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	// ChannelGroup allChannels = new DefaultChannelGroup("ChannelGroups",
	// GlobalEventExecutor.INSTANCE);

	protected final Hashids hashId = new Hashids("fenda", 6);

	private ChannelGroup allChannels = Singleton.get(WSServer.class).allChannels;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		System.out.println(111111);
		String text = msg.text();
		System.out.println(text);
		JSONObject jsonObject = new JSONObject(text);
		String code = jsonObject.getStr("code");
		String user = jsonObject.getStr("user");
		Integer isMaster = jsonObject.getInt("isMaster", 0);
		Long roomId = hashId.decode(code)[0];
		Long userId = hashId.decode(user)[0];

		FdRoom room = FdRoom.dao.findById(roomId);
		// if (isMaster.equals(1)) {
		// room.setMasterId(userId);
		// } else {
		// room.setUserId(userId);
		// }
		room.update();
		String wsUid = ctx.channel().id().asLongText();
		FdUser fdUser = FdUser.dao.findById(userId);
		fdUser.setWsUid(wsUid);
		System.out.println(text);
		fdUser.update();
		// Channel channel = ctx.channel();
		// System.out.println("read0");
		// System.out.println(channel.remoteAddress() + ": " + msg.text());

		Ret ret = Ret.by("status", 200);
		// ctx.channel().writeAndFlush(new TextWebSocketFrame(ret.toJson()));
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		System.out.println("连接" + ctx.channel().id().asLongText());
		allChannels.add(ctx.channel());
		// int size = allChannels.size();
		ctx.channel().writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText()));
		// allChannels.writeAndFlush(new TextWebSocketFrame(size + "来自服务端: "));
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		System.out.println("用户下线: " + ctx.channel().id().asLongText());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		LogKit.error("连接意外断了");
		ctx.channel().close();
	}
}